/**
 * 设置全局段号记录表，全局中断记录表
 */

#include "naskfunc.h"
#include "dsctbl.h"

/* 初始化GDT, IDT */
void init_gdtidt(void) {
	struct SEGMENT_DESCRIPTOR *gdt = (struct SEGMENT_DESCRIPTOR *) ADR_GDT;
	struct GATE_DESCRIPTOR *idt = (struct GATE_DESCRIPTOR *) ADR_IDT;
	int i;

	/* GDT初始化 0x270000~0x27ffff设定为GDT*/
	for (i = 0; i <= LIMIT_GDT / 8; i++) {//因为gdt占8字节所以要除8
		set_segmdesc(gdt + i, 0, 0, 0);
	}

	set_segmdesc(gdt + 1, 0xffffffff, 0x00000000, AR_DATA32_RW);
	set_segmdesc(gdt + 2, LIMIT_BOTPAK, ADR_BOTPAK, AR_CODE32_ER);//为bootparck.hrb准备
	load_gdtr(LIMIT_GDT, ADR_GDT);

	/* IDT初始化 0x26f800~0x26ffff设定为IDT*/
	for (i = 0; i <= LIMIT_IDT / 8; i++) {
		set_gatedesc(idt + i, 0, 0, 0);
	}
	load_idtr(LIMIT_IDT, ADR_IDT);
	set_gatedesc(idt + 0x0c, (int) asm_inthandler0c, 2 * 8, AR_INTGATE32); /* 设置INT 0x0c中断的门描述符 */
	set_gatedesc(idt + 0x0d, (int) asm_inthandler0d, 2 * 8, AR_INTGATE32); /* 设置INT 0x0d中断的门描述符 */
	set_gatedesc(idt + 0x20, (int) asm_inthandler20, 2 * 8, AR_INTGATE32); /* 设置INT 0x20中断的门描述符 */
	set_gatedesc(idt + 0x21, (int) asm_inthandler21, 2 * 8, AR_INTGATE32); /* 设置INT 0x21中断的门描述符 */
	//set_gatedesc(idt + 0x27, (int) asm_inthandler27, 2 * 8, AR_INTGATE32); /* 设置INT 0x27中断的门描述符 */
	set_gatedesc(idt + 0x2c, (int) asm_inthandler2c, 2 * 8, AR_INTGATE32); /* 设置INT 0x2c中断的门描述符 */
	// 如果将访问权限加上0x60的话，可以将段设置为应用程序用
	set_gatedesc(idt + 0x40, (int) asm_system_api, 2 * 8, AR_INTGATE32 + 0x60); /* 设置INT 0x40中断的门描述符 */
	return;
}

/* 设置段描述符
 *	sd 段描述符结构指针	limit 段限长	base 段基址		ar 段描述符属性
 */
void set_segmdesc(struct SEGMENT_DESCRIPTOR *sd, unsigned int limit, int base, int ar) {
	if (limit > 0xfffff) {/* 如果限长大于1M (20bit的段限长
	 若以字节为单位最多只能表示1M的内存)*/
		/* 描述符中有一个G位， 若G = 1则表示段限长是以4KB为单位若G = 0 则表示段限长是以字节为单位的 */
		ar |= 0x8000;/* G_bit = 1 */
		/* 调整段限长的值即除以4K */
		limit /= 0x1000;
	}
	sd->limit_low = limit & 0xffff;
	sd->base_low = base & 0xffff;
	sd->base_mid = (base >> 16) & 0xff;
	sd->access_right = ar & 0xff;
	sd->limit_high = ((limit >> 16) & 0x0f) | ((ar >> 8) & 0xf0);
	sd->base_high = (base >> 24) & 0xff;
	return;
}

/* 设置门描述符
 *	gd 门描述符结构指针		offset 过程入口偏移
 *	selector 段选择子		ar 门描述符属性
 */
void set_gatedesc(struct GATE_DESCRIPTOR *gd, int offset, int selector, int ar) {
	gd->offset_low = offset & 0xffff;
	gd->selector = selector;
	gd->dw_count = (ar >> 8) & 0xff;
	gd->access_right = ar & 0xff;
	gd->offset_high = (offset >> 16) & 0xffff;
	return;
}

